package com.weimob.mcloud.wechatwork.customer.facade.impl.customer;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.EmployeeBOConvertor;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.OrgDepartmentUserExport;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.data.EmployeeBO;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.data.OrgDepartmentBO;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.req.EmployeeDTO;
import com.weimob.mcloud.privacy.starter.enums.PrivacyDataType;
import com.weimob.mcloud.privacy.starter.service.PrivacyLimitsClient;
import com.weimob.mcloud.wechatwork.common.utils.JsonUtil;
import com.weimob.mcloud.wechatwork.core.base.MultiResponse;
import com.weimob.mcloud.wechatwork.core.base.SingleRequest;
import com.weimob.mcloud.wechatwork.core.base.SingleResponse;
import com.weimob.mcloud.wechatwork.core.entity.config.clue.ClueCfg;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.customer.Customer;
import com.weimob.mcloud.wechatwork.core.entity.relation.customer.CustomerLoseLog;
import com.weimob.mcloud.wechatwork.core.entity.relation.customer.CustomerLoseLogRequest;
import com.weimob.mcloud.wechatwork.core.enums.clue.PotentialRuleConditionEnum;
import com.weimob.mcloud.wechatwork.core.enums.clue.PotentialRuleTypeEnum;
import com.weimob.mcloud.wechatwork.core.enums.clue.PotentialSettingEnum;
import com.weimob.mcloud.wechatwork.core.service.clue.ClueService;
import com.weimob.mcloud.wechatwork.core.service.clue.request.ClueCfgQueryRequest;
import com.weimob.mcloud.wechatwork.core.service.clue.request.ClueCfgRequest;
import com.weimob.mcloud.wechatwork.core.service.customer.CustomerLoseService;
import com.weimob.mcloud.wechatwork.customer.constant.ExportConstants;
import com.weimob.mcloud.wechatwork.customer.domain.enums.WosExporterEnum;
import com.weimob.mcloud.wechatwork.customer.enums.TouchTaskTypeEnum;
import com.weimob.mcloud.wechatwork.customer.redis.RedisService;
import com.weimob.mcloud.wechatwork.customer.service.TagManageService;
import com.weimob.mcloud.wechatwork.customer.service.user.base.BaseRequest;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.TagSourceEnum;
import com.weimob.mcloud.wechatwork.customer.service.user.exception.BaseErrorCode;
import com.weimob.mcloud.wechatwork.customer.service.user.exception.BizException;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.customer.AdminInfo;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.customer.CustomerLoseLogBO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.customer.CustomerPageResponse;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.customer.EmployDeleteCustomerAlarmBO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.tag.TagBO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.dto.customer.CustomerLoseLogQueryDTO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.dto.customer.EmployDeleteCustomerAlarmDTO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.req.tag.CustomerTagQueryDTO;
import com.weimob.mcloud.wechatwork.customer.service.user.utils.BeanUtil;
import com.weimob.mcloud.wechatwork.customer.service.user.utils.SoaResponseUtil;
import com.weimob.mcloud.wechatwork.customer.third.PrivateSphereThird;
import com.weimob.mcloud.wechatwork.customer.third.core.CustomerServiceProxy;
import com.weimob.mcloud.wechatwork.customer.utils.BeanCopierUtil;
import com.weimob.mcloud.wechatwork.customer.utils.DateUtils;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import com.weimob.wechatwork.wechatworkexporter.ExportService;
import com.weimob.wechatwork.wechatworkexporter.req.ExportTaskSaveDTO;
import com.weimob.wechatwork.wechatworkexporter.vo.ExportTaskSaveVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 流失客户
 **/
@Slf4j
@Service
public class CustomerLoseFacade {

    @Autowired
    private PrivateSphereThird privateSphereThird;

    @Reference
    private CustomerLoseService customerLoseService;

    @Autowired
    private CustomerServiceProxy customerServiceProxy;

    @Reference
    private OrgDepartmentUserExport orgDepartmentUserExport;

    @Reference
    private ClueService clueService;

    @Autowired
    private RedisService redisService;

    @Reference
    private ExportService exportService;

    @Autowired
    private TagManageService tagManageService;

    @Autowired
    @Qualifier("queryCustomerLoseThreadPool")
    private ThreadPoolTaskExecutor queryCustomerLoseThreadPool;

    @Autowired
    private PrivacyLimitsClient privacyLimitsClient;

    /**
     * 企微助手产品id
     */
    @Value("${aewc.productId:203}")
    private Long aewcProductId;


    public CustomerPageResponse<CustomerLoseLogBO> query(CustomerLoseLogQueryDTO customerLoseLogQueryDTO) {
        CustomerPageResponse<CustomerLoseLogBO> pageResponse = new CustomerPageResponse<>();
        //1、获取私域信息
        PrivateSphere privateSphere = privateSphereThird.fetch(customerLoseLogQueryDTO.getBasicInfo(), Boolean.TRUE);
        //默认值赋值
        Date loseStartTime = customerLoseLogQueryDTO.getLoseStartTime();
        Date loseEndTime = customerLoseLogQueryDTO.getLoseEndTime();
        if (Objects.isNull(loseStartTime) || Objects.isNull(loseEndTime)) {
            Calendar instance = Calendar.getInstance();
            instance.set(Calendar.HOUR_OF_DAY, 0);
            instance.set(Calendar.MINUTE, 0);
            instance.set(Calendar.SECOND, 0);
            //默认查近6个月数据
            instance.add(Calendar.MONTH, -6);
            customerLoseLogQueryDTO.setLoseStartTime(instance.getTime());
            customerLoseLogQueryDTO.setLoseEndTime(new Date());
        }

        CustomerLoseLogRequest customerLoseLogRequest = new CustomerLoseLogRequest();
        BeanUtil.copyProperties(customerLoseLogQueryDTO, customerLoseLogRequest);

        SingleRequest<CustomerLoseLogRequest> request = new SingleRequest<>(customerLoseLogRequest, customerLoseLogQueryDTO.getPageNum(), customerLoseLogQueryDTO.getPageSize());
        request.setPrivateSphere(privateSphere);
        MultiResponse<CustomerLoseLog> response = SoaUtil.unpack(customerLoseService.query(request));

        if (CollectionUtils.isEmpty(response.getDataList())) {
            pageResponse.setTotalCount(0L);
            return pageResponse;
        }

        List<String> customerIdList = new ArrayList<>();
        List<String> orgUserId = new ArrayList<>();
        if (!CollectionUtils.isEmpty(response.getDataList())) {
            for (CustomerLoseLog customerLoseLog : response.getDataList()) {
                customerIdList.add(customerLoseLog.getCustomerId());
                orgUserId.add(customerLoseLog.getOrgUserId());
            }
        }

        Map<String, String> customerNameMap = new HashMap<>();
        //查客户昵称
        if (!CollectionUtils.isEmpty(customerIdList)) {
            try {
                List<Customer> customerList = customerServiceProxy.fetchCustomerByIds(customerIdList, null, privateSphere);
                if (!CollectionUtils.isEmpty(customerList)) {
                    for (Customer customer : customerList) {
                        customerNameMap.put(customer.getId(), customer.getName());
                    }
                }
            } catch (Exception e) {
                log.error("查询客户信息失败,error",e);
            }
        }

        //查员工名称
        Map<String, String> orgUserNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgUserId)) {
            EmployeeDTO employeeDTO = new EmployeeDTO();
            employeeDTO.setIds(orgUserId);
            employeeDTO.setExceptDeleted(true);
            employeeDTO.setBosId(customerLoseLogQueryDTO.getBasicInfo().getBosId());
            List<EmployeeBO> employeeBOList = SoaUtil.unpack(orgDepartmentUserExport.getUsersByIds(employeeDTO));
            if (!CollectionUtils.isEmpty(employeeBOList)) {
                for (EmployeeBO employeeBO : employeeBOList) {
                    orgUserNameMap.put(employeeBO.getOrgUserId(), EmployeeBOConvertor.getEmployeeDisplayName(employeeBO));
                }
            }
        }

        Map<String, List<TagBO>> tagMap = new HashMap<>();
        CountDownLatch countDownLatch = new CountDownLatch(response.getDataList().size());
        for (CustomerLoseLog customerLoseLog : response.getDataList()) {
            queryCustomerLoseThreadPool.submit(() -> {
                try {
                    //补充当前客户标签信息
                    try {

                        String customerId = customerLoseLog.getCustomerId();

                        Customer customer = customerServiceProxy.fetchCustomer(customerId, null, privateSphere);
                        if (customer == null) {
                            log.error("客户流失未查到客户信息，customerId:{}", customerId);
                            return;
                        }
                        String externalUserId = customer.getExternalUserid();

                        CustomerTagQueryDTO customerTagQueryDTO = new CustomerTagQueryDTO();
                        BeanUtils.copyProperties(customerLoseLogQueryDTO.getBasicInfo(), customerTagQueryDTO);
                        customerTagQueryDTO.setExternalUserId(externalUserId);
                        List<TagBO> tagBOS = tagManageService.queryCustomerTag(customerTagQueryDTO);
                        if (!CollectionUtils.isEmpty(tagBOS)) {
                            List<String> tagList = new ArrayList<>();
                            for (TagBO tagBO : tagBOS) {
                                tagList.add(tagBO.getTagGroupBO().getTagGroupName() + "|" + tagBO.getTagName());
                            }
                            tagMap.put(customerLoseLog.getCustomerId(), tagBOS);
                        }
                    } catch (Exception e) {
                        log.error("客户流失补充当前客户标签信息失败，message:{}", e.getMessage());
                    }
                } catch (Exception e) {
                    log.error("客户流失单条客户数据补充失败，message:{}，客户:{}", e.getMessage(), customerLoseLog);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        try {
            boolean await = countDownLatch.await(5, TimeUnit.SECONDS);
            if (Boolean.FALSE.equals(await)) {
                log.error("客户流失列表补充标签信息超时");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("InterruptedException e", e);
        } catch (Exception e) {
            log.error("客户流失列表失败，message:", e);
        }

        List<CustomerLoseLogBO> result = new ArrayList<>();
        CustomerLoseLogBO customerLoseLogBO = null;
        for (CustomerLoseLog customerLoseLog : response.getDataList()) {
            customerLoseLogBO = new CustomerLoseLogBO();
            BeanUtil.copyProperties(customerLoseLog, customerLoseLogBO);
            customerLoseLogBO.setCustomerName(customerNameMap.get(customerLoseLog.getCustomerId()));
            customerLoseLogBO.setUserName(orgUserNameMap.get(customerLoseLog.getOrgUserId()));
            customerLoseLogBO.setTags(tagMap.get(customerLoseLog.getCustomerId()));
            if (customerLoseLogBO.getLastTouchType() != null) {
                TouchTaskTypeEnum touchTaskTypeEnum = TouchTaskTypeEnum.getEnumByCode(customerLoseLogBO.getLastTouchType());
                if (touchTaskTypeEnum != null) {
                    customerLoseLogBO.setLastTouchInformation("【" + touchTaskTypeEnum.getDesc() + "】"
                            + customerLoseLogBO.getLastTouchInformation());
                }

            }
            result.add(customerLoseLogBO);
        }
        pageResponse.setResults(result);
        pageResponse.setTotalCount(response.getTotalCount());
        pageResponse.setPageNum(response.getPageNum());
        pageResponse.setPageSize(response.getPageSize());
        pageResponse.setTotalPage(response.getTotalPage());
        return pageResponse;
    }

    public Boolean customerDeleteEmployListExport(CustomerLoseLogQueryDTO customerLoseLogQueryDTO) {
        PrivateSphere privateSphereResult = privateSphereThird.fetch(customerLoseLogQueryDTO.getBasicInfo(), Boolean.TRUE);

        //step 1 查看当前bos_id+wid是否在30秒内已经导出过了
        Boolean checkExport = checkExport(customerLoseLogQueryDTO);
        if (!checkExport) {
            //抛出异常
            throw new BizException(BaseErrorCode.USER_EXPORT_SUBMIT_TIME.getCode(), BaseErrorCode.USER_EXPORT_SUBMIT_TIME.getMsg());
        }
        //step 2 判断要导出的数据量是否超过100万
        CustomerLoseLogQueryDTO queryBo = new CustomerLoseLogQueryDTO();
        BeanCopierUtil.copyProperties(customerLoseLogQueryDTO, queryBo);
        queryBo.setBasicInfo(customerLoseLogQueryDTO.getBasicInfo());
        queryBo.setPageSize(1);
        queryBo.setPageNum(1);
        CustomerPageResponse<CustomerLoseLogBO> query = query(queryBo);
        Long totalCount = query.getTotalCount();
        if (totalCount != 0 && totalCount > 100_0000) {
            throw new BizException(BaseErrorCode.USER_EXPORT_MAX_LIMIT.getCode(), BaseErrorCode.USER_EXPORT_MAX_LIMIT.getMsg());
        }

        //step 3 创建导出任务
        ExportTaskSaveDTO exportTaskSaveDTO = new ExportTaskSaveDTO();
        exportTaskSaveDTO.setBosId(privateSphereResult.getBosId());
        exportTaskSaveDTO.setWid(customerLoseLogQueryDTO.getWid());
        if (customerLoseLogQueryDTO.getLoseType() == 1) {
            //客户删除员工
            exportTaskSaveDTO.setFileName(WosExporterEnum.CUSTOMER_DELETE_ORG.getFileName() + "-" + DateUtils.getTodayDate());
            exportTaskSaveDTO.setTaskType(WosExporterEnum.CUSTOMER_DELETE_ORG.getBizType());
        } else if (customerLoseLogQueryDTO.getLoseType() == 2) {
            //员工删除客户
            exportTaskSaveDTO.setFileName(WosExporterEnum.ORG_DELETE_CUSTOMER.getFileName() + "-" + DateUtils.getTodayDate());
            exportTaskSaveDTO.setTaskType(WosExporterEnum.ORG_DELETE_CUSTOMER.getBizType());
        }
        exportTaskSaveDTO.setVid(customerLoseLogQueryDTO.getBasicInfo().getVid());
        exportTaskSaveDTO.setProductId(privateSphereResult.getProductId());
        exportTaskSaveDTO.setParams(JsonUtil.obj2Str(customerLoseLogQueryDTO));
        SoaResponse<ExportTaskSaveVo, Void> exportTaskSaveVoVoidSoaResponse = exportService.saveExportTask(exportTaskSaveDTO);
        if (!SoaResponseUtil.isSuccNotNull(exportTaskSaveVoVoidSoaResponse)) {
            throw new BizException(Long.valueOf(exportTaskSaveVoVoidSoaResponse.getReturnCode()), exportTaskSaveVoVoidSoaResponse.getReturnMsg());
        }
        return Boolean.TRUE;
    }

    /**
     * 判断当前bosID+wid 30秒内是否创建过导出任务
     */
    private Boolean checkExport(CustomerLoseLogQueryDTO customerLoseLogQueryDTO) {
        Long wid = customerLoseLogQueryDTO.getWid();
        Long bosId = customerLoseLogQueryDTO.getBasicInfo().getBosId();
        String redisKey = ExportConstants.CUSTOMER_LOSE_EXPORT + bosId + ":" + wid;
        return redisService.setNXAndExpire(redisKey, NumberUtils.LONG_ONE.toString(), ExportConstants.MAX_EXPIRE_TIME, TimeUnit.SECONDS);
    }

    /**
     * 报警保存
     */
    public Boolean employDeleteCustomerAlarm(EmployDeleteCustomerAlarmDTO employDeleteCustomerAlarmDTO) {

        //1、获取私域信息
        PrivateSphere privateSphere = privateSphereThird.fetch(employDeleteCustomerAlarmDTO.getBasicInfo(), Boolean.TRUE);

        ClueCfgRequest clueCfgRequest = new ClueCfgRequest();
        List<ClueCfg> cfgDataList = new ArrayList<>();
        cfgDataList.add(toClueCfg(employDeleteCustomerAlarmDTO, privateSphere.getPrivateSphereId()));
        clueCfgRequest.setCfgDataList(cfgDataList);

        SingleRequest<ClueCfgRequest> request = new SingleRequest(clueCfgRequest);
        request.setPrivateSphere(privateSphere);
        SingleResponse<Boolean> unpack = SoaUtil.unpack(clueService.createOrUpdateClueCfgForCustomerLose(request));

        return unpack.getData();
    }

    private ClueCfg toClueCfg(EmployDeleteCustomerAlarmDTO employDeleteCustomerAlarmDTO, String privateSphereId) {
        ClueCfg clueCfg = new ClueCfg();
        clueCfg.setPrivateSphereId(privateSphereId);
        clueCfg.setId(employDeleteCustomerAlarmDTO.getId());
        clueCfg.setPotentialRuleTypeEnum(PotentialRuleTypeEnum.DAY);
        clueCfg.setPotentialSettingEnum(PotentialSettingEnum.WARN);
        clueCfg.setRuleConditionEnum(PotentialRuleConditionEnum.GER);
        clueCfg.setRuleOpenFlag(employDeleteCustomerAlarmDTO.getStatus());
        clueCfg.setRuleEventValue(Long.valueOf(employDeleteCustomerAlarmDTO.getDeleteNum()));
        clueCfg.setRuleExtendInfo(JSON.toJSONString(employDeleteCustomerAlarmDTO.getNoticeAdmin()));
        return clueCfg;
    }

    public EmployDeleteCustomerAlarmBO getAlarmDetail(BaseRequest request) {
        EmployDeleteCustomerAlarmBO result = new EmployDeleteCustomerAlarmBO();
        //1、获取私域信息
        PrivateSphere privateSphere = privateSphereThird.fetch(request.getBasicInfo(), Boolean.TRUE);

        ClueCfgQueryRequest clueCfgQueryRequest = new ClueCfgQueryRequest();
        clueCfgQueryRequest.setRuleId(PotentialSettingEnum.WARN.getCode());

        SingleRequest<ClueCfgQueryRequest> cfgQueryRequest = new SingleRequest(clueCfgQueryRequest);
        cfgQueryRequest.setPrivateSphere(privateSphere);
        MultiResponse<ClueCfg> clueCfgResponse = SoaUtil.unpack(clueService.fetchAllClueCfg(cfgQueryRequest));
        if (clueCfgResponse != null && !CollectionUtils.isEmpty(clueCfgResponse.getDataList()) && clueCfgResponse.getDataList().get(0) != null) {
            result = toEmployDeleteCustomerAlarmBO(clueCfgResponse.getDataList().get(0), request.getBasicInfo().getBosId());
        }
        return result;
    }

    private EmployDeleteCustomerAlarmBO toEmployDeleteCustomerAlarmBO(ClueCfg clueCfg, Long bosId) {
        EmployDeleteCustomerAlarmBO employDeleteCustomerAlarmBO = new EmployDeleteCustomerAlarmBO();
        employDeleteCustomerAlarmBO.setId(clueCfg.getId());
        employDeleteCustomerAlarmBO.setDeleteNum(Math.toIntExact(clueCfg.getRuleEventValue()));
        employDeleteCustomerAlarmBO.setStatus(clueCfg.getRuleOpenFlag());
        List<String> orgUserIds = JSONArray.parseArray(clueCfg.getRuleExtendInfo(), String.class);
        if (!CollectionUtils.isEmpty(orgUserIds)) {
            EmployeeDTO employeeDTO = new EmployeeDTO();
            employeeDTO.setIds(orgUserIds);
            employeeDTO.setExceptDeleted(true);
            employeeDTO.setBosId(bosId);
            List<EmployeeBO> employeeBOList = SoaUtil.unpack(orgDepartmentUserExport.getUsersByIds(employeeDTO));
            List<AdminInfo> noticeAdmin = new ArrayList<>();
            AdminInfo adminInfo = null;
            if (!CollectionUtils.isEmpty(employeeBOList)) {
                for (EmployeeBO employeeBO : employeeBOList) {
                    adminInfo = new AdminInfo();
                    adminInfo.setOrgUserId(employeeBO.getOrgUserId());
                    adminInfo.setName(EmployeeBOConvertor.getEmployeeDisplayName(employeeBO));
                    if (!CollectionUtils.isEmpty(employeeBO.getOrgDepartmentListBOs())) {
                        adminInfo.setDepartmentId(employeeBO.getOrgDepartmentListBOs().get(0).get(0).getDepartmentId());
                    }
                    noticeAdmin.add(adminInfo);
                }
                employDeleteCustomerAlarmBO.setNoticeAdmin(noticeAdmin);
            }
        }
        return employDeleteCustomerAlarmBO;
    }

    public CustomerPageResponse<CustomerLoseLogBO> customerLoseExportInfo(CustomerLoseLogQueryDTO customerLoseLogQueryDTO) {
        CustomerPageResponse<CustomerLoseLogBO> pageResponse = new CustomerPageResponse<>();
        //1、获取私域信息
        PrivateSphere privateSphere = privateSphereThird.fetch(customerLoseLogQueryDTO.getBasicInfo(), Boolean.TRUE);

        CustomerLoseLogRequest customerLoseLogRequest = new CustomerLoseLogRequest();
        BeanUtil.copyProperties(customerLoseLogQueryDTO, customerLoseLogRequest);

        SingleRequest<CustomerLoseLogRequest> request = new SingleRequest<>(customerLoseLogRequest, customerLoseLogQueryDTO.getPageNum(), customerLoseLogQueryDTO.getPageSize());
        request.setPrivateSphere(privateSphere);
        MultiResponse<CustomerLoseLog> response = SoaUtil.unpack(customerLoseService.query(request));

        if (CollectionUtils.isEmpty(response.getDataList())) {
            return pageResponse;
        }

        List<String> customerIdList = new ArrayList<>();
        List<String> orgUserIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(response.getDataList())) {
            for (CustomerLoseLog customerLoseLog : response.getDataList()) {
                customerIdList.add(customerLoseLog.getCustomerId());
                orgUserIds.add(customerLoseLog.getOrgUserId());
            }
        }

        Map<String, Customer> customerMap = new HashMap<>();
        //查客户昵称
        if (CollectionUtils.isNotEmpty(customerIdList)) {
            try {
                List<Customer> customerList = customerServiceProxy.fetchCustomerByIds(customerIdList, null, privateSphere);
                if (!CollectionUtils.isEmpty(customerList)) {
                    for (Customer customer : customerList) {
                        customerMap.put(customer.getId(), customer);
                    }
                }
            } catch (Exception e) {
                log.error("查询客户信息失败,error", e);
            }
        }

        //查员工名称
        Map<String, String> orgUserNameMap = new HashMap<>();
        Map<String, String> deptNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgUserIds)) {
            EmployeeDTO employeeDTO = new EmployeeDTO();
            employeeDTO.setIds(orgUserIds);
            employeeDTO.setExceptDeleted(true);
            employeeDTO.setFetchParentDepartment(true);
            employeeDTO.setBosId(customerLoseLogQueryDTO.getBasicInfo().getBosId());
            List<EmployeeBO> employeeBOList = SoaUtil.unpack(orgDepartmentUserExport.getUsersByIds(employeeDTO));
            if (!CollectionUtils.isEmpty(employeeBOList)) {
                for (EmployeeBO employeeBO : employeeBOList) {
                    orgUserNameMap.put(employeeBO.getOrgUserId(), EmployeeBOConvertor.getEmployeeDisplayName(employeeBO));
                    //部门
                    if (!CollectionUtils.isEmpty(employeeBO.getOrgDepartmentListBOs())
                            && !CollectionUtils.isEmpty(employeeBO.getOrgDepartmentListBOs().get(0))) {
                        String finalDepartmentName = "";
                        for (List<OrgDepartmentBO> orgDepartmentList : employeeBO.getOrgDepartmentListBOs()) {
                            String singleDepartmentName = "";
                            for (int i = orgDepartmentList.size() - 1; i >= 0; i--) {
                                OrgDepartmentBO orgDepartmentBO = orgDepartmentList.get(i);
                                singleDepartmentName += orgDepartmentBO.getName() + "/";
                            }

                            finalDepartmentName += singleDepartmentName + "、";
                        }
                        deptNameMap.put(employeeBO.getOrgUserId(), finalDepartmentName);
                    }
                }
            }
        }

        Map<String, String> wechatTagMap = new HashMap<>();
        Map<String, String> weimobTagMap = new HashMap<>();

        CountDownLatch countDownLatch = new CountDownLatch(response.getDataList().size());
        for (CustomerLoseLog customerLoseLog : response.getDataList()) {
            queryCustomerLoseThreadPool.submit(() -> {
                try {
                    //补充当前客户标签信息
                    try {

                        String customerId = customerLoseLog.getCustomerId();

                        Customer customer = customerServiceProxy.fetchCustomer(customerId, null, privateSphere);

                        if (customer == null) {
                            log.error("客户流失未查到客户信息，customerId:{}", customerId);
                            return;
                        }
                        String externalUserId = customer.getExternalUserid();

                        CustomerTagQueryDTO customerTagQueryDTO = new CustomerTagQueryDTO();
                        BeanUtils.copyProperties(customerLoseLogQueryDTO.getBasicInfo(), customerTagQueryDTO);
                        customerTagQueryDTO.setExternalUserId(externalUserId);
                        List<TagBO> tagBOS = tagManageService.queryCustomerTag(customerTagQueryDTO);
                        List<String> wechatTagList = new ArrayList<>();
                        List<String> weimobTagList = new ArrayList<>();
                        if (CollectionUtils.isNotEmpty(tagBOS)) {
                            for (TagBO tagBO : tagBOS) {
                                // 区分企微标签 微盟标签
                                if (TagSourceEnum.WECHAT.getSource().equals(tagBO.getTagSource())) {
                                    wechatTagList.add(tagBO.getTagGroupBO().getTagGroupName() + "|" + tagBO.getTagName());
                                } else {
                                    weimobTagList.add(tagBO.getTagGroupBO().getTagGroupName() + "|" + tagBO.getTagName());
                                }
                            }
                        }
                        wechatTagMap.put(customerLoseLog.getCustomerId(), Joiner.on("、").join(wechatTagList));
                        weimobTagMap.put(customerLoseLog.getCustomerId(), Joiner.on("、").join(weimobTagList));
                    } catch (Exception e) {
                        log.error("客户流失补充当前客户标签信息失败，message:{}", e.getMessage());
                    }
                } catch (Exception e) {
                    log.error("客户流失单条客户数据补充失败，message:{}，客户:{}", e.getMessage(), customerLoseLog);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        try {
            boolean await = countDownLatch.await(5, TimeUnit.SECONDS);
            if (Boolean.FALSE.equals(await)) {
                log.error("客户流失列表补充客户标签信息超时");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("InterruptedException e", e);
        } catch (Exception e) {
            log.error("客户流失列表失败，message:{}", e.getMessage());
        }

        List<CustomerLoseLogBO> result = new ArrayList<>();
        CustomerLoseLogBO customerLoseLogBO = null;

        Boolean privacyFlag = privacyLimitsClient.corpBackendIfNeedDesensitize(
                customerLoseLogQueryDTO.getWid(), privateSphere.getBosId(), PrivacyDataType.ExportData);
        for (CustomerLoseLog customerLoseLog : response.getDataList()) {
            customerLoseLogBO = new CustomerLoseLogBO();
            BeanUtil.copyProperties(customerLoseLog, customerLoseLogBO);
            if (customerLoseLog.getLastTouchType() != null) {
                TouchTaskTypeEnum enumByCode = TouchTaskTypeEnum.getEnumByCode(customerLoseLog.getLastTouchType());
                if (enumByCode != null) {
                    customerLoseLogBO.setLastTouchWay(enumByCode.getDesc());
                }
            }
            Customer customer = customerMap.get(customerLoseLog.getCustomerId());
            if (customer != null) {
                customerLoseLogBO.setUnionID(customer.getUnionid());
                if (StringUtils.isNotBlank(customer.getPhone())) {
                    if (privacyFlag) {
                        //手机号脱敏
                        String privacyPhone = PrivacyLimitsClient.mobilePhone(customer.getPhone());
                        customerLoseLogBO.setPhones(Lists.newArrayList(privacyPhone));
                    } else {
                        customerLoseLogBO.setPhones(Lists.newArrayList(customer.getPhone()));
                    }
                }
                customerLoseLogBO.setCustomerName(customer.getName());
            }
            customerLoseLogBO.setUserName(orgUserNameMap.get(customerLoseLog.getOrgUserId()));
            customerLoseLogBO.setDepartmentName(deptNameMap.get(customerLoseLog.getOrgUserId()));
            customerLoseLogBO.setWeimobTag(weimobTagMap.get(customerLoseLog.getCustomerId()));
            customerLoseLogBO.setWechatTag(wechatTagMap.get(customerLoseLog.getCustomerId()));
            result.add(customerLoseLogBO);
        }
        pageResponse.setResults(result);
        pageResponse.setTotalCount(response.getTotalCount());
        pageResponse.setPageNum(response.getPageNum());
        pageResponse.setPageSize(response.getPageSize());
        pageResponse.setTotalPage(response.getTotalPage());
        return pageResponse;
    }
}
